<?php

require_once 'BluesCoders/Context/Builder/Standart.php';

/**
 * Description of Xml
 *
 * @author miho
 */
class BluesCoders_Context_Builder_Xml extends BluesCoders_Context_Builder_Standart{

    protected $_path;

    public function  __construct(BluesCoders_Context $parent = null) {
        parent::__construct($parent);
    }

    public static function build($path, $basePath, $parent = null) {
        $builder = new BluesCoders_Context_Builder_Xml($parent);
        $builder->setBasePath($basePath);
        try{
            return $builder->setPath($path)->_load();
        }catch(Exception $e) {
            throw new Exception(sprintf('Error while building context, nested exception is "%s"',$e->getMessage()));        }
    }


    protected function _load() {
        if(is_null($this->_path)) throw new Exception("Path must be setted!!");

        if(! file_exists($this->_path)) throw new Exception("Path " . $this->_path . " is invalid");

        $xml = simplexml_load_file($this->_path);
        foreach($xml->loader as $loader) {
            var_dump($loader);
        }

        foreach($xml->bean as $bean) {
            //var_dump($bean);
            $descriptor = new BluesCoders_Context_Descriptor();
            $descriptor->setId(''.$bean['id'])->setClass(''.$bean['class']);
            

            foreach($bean->property as $property) {
                if(! isset($property['name'])){
                    throw new Exception(sprintf('Bean property shoud have name'));
                }

                if(isset($property['ref'])){
                    $propertyRef = $this->getBean(''.$property['ref']);
                }else if($property->map) {
                    $propertyRef = $this->_createMap($property->map);
                }else{
                    $propertyRef = ''.$property;
                }

                $descriptor->addProperty(''.$property['name'], $propertyRef);
            }
            
            $this->createBean($descriptor);

        }
        
        return $this;
    }

    public function getPath() {
        return $this->_path;
    }

    public function setPath($value) {
        $this->_path = $this->_basePath .DIRECTORY_SEPARATOR. $value;
        return $this;
    }

    protected function _createMap($xmlMap) {
        $map = array();

        foreach($xmlMap->entry as $entry) {
            $map[''.$entry['key']] = ''.$entry;
        }

        //var_dump($map);

        return $map;
    }

}
?>
